using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace Emlyn.Common.Data.SqlServer.SqlManagers
{
    internal class SqlManagerConnection
    {
        string _connectionString;
        SqlConnection _connection;
        SqlTransaction _transaction;
        int _transactionLevel;

        private void Initialise()
        {
            _connection = null;
            _transaction = null;
            _transactionLevel = 0;
        }

        public SqlManagerConnection(string aConnectionString)
        {
            _connectionString = aConnectionString;
            Initialise();
        }

        public SqlConnection Connection
        {
            get
            {
                return _connection;
            }
        }

        public SqlTransaction Transaction
        {
            get
            {
                return _transaction;
            }
        }

        public void BeginTransaction()
        {
            if (_transaction == null)
            {
                _connection = new SqlConnection(_connectionString);
                _connection.Open();
                _transaction = _connection.BeginTransaction();
                _transactionLevel = 1;
            }
            else
            {
                _transactionLevel++;
            };
        }

        public void Commit()
        {
            if (_transaction != null)
            {
                _transactionLevel--;
                if (_transactionLevel <= 0)
                {
                    SqlTransaction ltransaction = _transaction;
                    SqlConnection lconnection = _connection;
                    _transaction = null;
                    _connection = null;
                    try
                    {
                        ltransaction.Commit();
                    }
                    finally
                    {
                        lconnection.Dispose();
                    }
                }
            }
            else
                throw new ApplicationException("Can't commit, not inside a transaction");
        }

        public void Rollback()
        {
            if (_transaction != null)
            {
                SqlTransaction ltransaction = _transaction;
                SqlConnection lconnection = _connection;
                _transaction = null;
                _transactionLevel = 0;
                _connection = null;
                try
                {
                    ltransaction.Commit();
                }
                finally
                {
                    lconnection.Dispose();
                }
            }
            else
                throw new ApplicationException("Can't rollback, not inside a transaction");
        }
    }
}
